﻿using APIDemo2.Utils;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace APIDemo2.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class HttpClientTestController : ControllerBase
    {
        [HttpGet]
        public async Task<string> TestHttpClient()
        {
            for (int i = 1; i <= 100; i++)
            {
                await TestHttpClient(i);
            }

            return "ok";
        }
        [HttpGet]
        public async Task<string> TestHttpClientSingleton()
        {
            for (int i = 1; i <= 100; i++)
            {
                await TestHttpSingleton(i);
            }

            return "ok";
        }

        private async Task TestHttpClient(int times)
        {
            string baiduUri = "http://localhost:5173/WeatherForecast";
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    HttpResponseMessage response = await client.GetAsync(baiduUri);
                    response.EnsureSuccessStatusCode();
                    string result = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"HttpClient第{times}次执行");
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine($"HttpClient第{times}次抛出异常：" + e.Message, e);
                }
            }
        }

        private async Task TestHttpSingleton(int times)
        {
            string baiduUri = "http://localhost:5173/WeatherForecast";
            var client = HttpClientFactoryUtil.Instance.CreateClient();
            try
            {
                HttpResponseMessage response = await client.GetAsync(baiduUri);
                response.EnsureSuccessStatusCode();
                string tokenResult = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"HttpSingleton第{times}次执行");
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"HttpSingleton第{times}次抛出异常：" + e.Message, e);
            }
        }
    }
}
